package com.igeek.ssm.controller;

import com.igeek.ssm.entity.User;
import com.igeek.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Description TODO
 * @Author chenmin
 * @Version 1.0
 * @Date 2023/2/9 15:26
 */
@Controller
public class UserController {

    @Autowired(required = false)
    private UserService userService;

    //查看用户列表

    @GetMapping("/basic_table.html")
    public String table(Model model){
        List<User> users = userService.findAll();
        model.addAttribute("users",users);
        return "basic_table";
    }


    //跳转至表单页面
    @GetMapping("form_layouts.html")
    public String form(){
        return "form_layouts";
    }

    @PostMapping("/register")
    public String register(User user,
                           @RequestPart("photo")MultipartFile photo,
                           @RequestPart("photos")MultipartFile[] photos
    ) throws IOException {
        if(photo!=null){
            String filename = photo.getOriginalFilename();
            if(StringUtils.hasLength(filename)){
                String newName = UUID.randomUUID()+filename.substring(filename.lastIndexOf("."));
                //图片服务器写一份
                photo.transferTo(new File("G:\\temp\\img\\"+newName));
                //用户设置头像
                user.setPic("/img/"+newName);
            }
        }

        //处理多个上传的头像信息
        if(photos!=null && photos.length>0){
            for (MultipartFile file : photos) {
                String filename = file.getOriginalFilename();
                if(StringUtils.hasLength(filename)){
                    String newName = UUID.randomUUID()+filename.substring(filename.lastIndexOf("."));
                    //图片服务器写一份
                    file.transferTo(new File("G:\\temp\\img\\"+newName));
                }
            }
        }

        boolean flag = userService.register(user);
        if(flag){
            //响应重定向 显示目标地址，避免刷新网页地址时重复提交表单
            return "redirect:/basic_table.html";
        }
        //数据回显
        return "/form_layouts.html";
    }

}
